package com.hanhanxiaochong.zhongxiangchuanmei.view.home.act;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.alipay.Alipay;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.PriceBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.WXPayBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.AppointmentPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IAppointmentView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.my.CouponActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.checkbox.SmoothCheckBox;
import com.hanhanxiaochong.zhongxiangchuanmei.wxapi.WXPayUtils;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/2.
 * Desc   : 立即预约act
 */

public class AppointmentActivity extends BaseActivity<AppointmentPresenter> implements IAppointmentView {
    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.cb_alipay)
    SmoothCheckBox cbAlipay;
    @BindView(R.id.cb_wechat)
    SmoothCheckBox cbWechat;
    @BindView(R.id.cb_bank)
    SmoothCheckBox cbBank;
    @BindView(R.id.tv_tech_name)
    TextView tvTechName;
    @BindView(R.id.tv_appoint_time)
    TextView tvAppointTime;
    @BindView(R.id.tv_coupon_name)
    TextView tvCouponName;
    @BindView(R.id.txt_appointment)
    TextView txtAppointment;

    private static final int REQUEST_COUPON = 0x0001;

    //门店id
    private String s_id;
    //项目id
    private String p_id;
    //技师id
    private String tech_id;
    //优惠券id
    private String coupon_id = "";
    private String token;
    private String price;
    //支付方式 1微信,2支付宝,3银联,4余额
    private String payment = "2";
    private String serviceCode;

    public static Intent createIntent(Context context, String s_id, String p_id) {
        Intent intent = new Intent(context, AppointmentActivity.class);
        intent.putExtra("s_id", s_id);
        intent.putExtra("p_id", p_id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_appointment);
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
        Intent intent = getIntent();
        s_id = intent.getStringExtra("s_id");
        p_id = intent.getStringExtra("p_id");
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initPresenter() {
        mPresenter = new AppointmentPresenter(this);
    }

    @Override
    protected void init() {
        setTopView();
        txtMoney.setText("金额计算中");
        mPresenter.caculatePrice(token, p_id, coupon_id);

        cbAlipay.setChecked(true);
        //支付宝
        cbAlipay.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "2";
                cbWechat.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //微信
        cbWechat.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "1";
                cbAlipay.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //银联
        cbBank.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "3";
                cbWechat.setChecked(false);
                cbAlipay.setChecked(false);
            }
        });
    }

    private void setTopView() {
        imgLeft.setImageResource(R.mipmap.icon_close_black);
        txtTitle.setText("立即预约");
    }

    @OnClick({R.id.ll_leftview, R.id.ll_choose_technician, R.id.ll_choose_time, R.id
            .ll_choose_coupon, R.id.txt_appointment, R.id.ll_alipay, R.id.ll_wechat, R.id.ll_paypal})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.ll_choose_technician:
                startActivity(TechnicianActivity.createIntent(this, s_id, p_id));
                break;
            case R.id.ll_choose_time:
                startActivity(AppointmentTimeActivity.createIntent(this));
                break;
            case R.id.ll_choose_coupon:
                startActivityForResult(CouponActivity.createIntent(this, "project", p_id), REQUEST_COUPON);
                break;
            case R.id.txt_appointment:
                if (tech_id == null) {
                    ToastUtils.showToast("请选择技师");
                    return;
                }
                if (tvAppointTime.getText().toString().equals("")) {
                    ToastUtils.showToast("请选择预约时间");
                    return;
                }
                if (price == null) {
                    ToastUtils.showToast("金额计算中,请稍候");
                    return;
                }
                mPresenter.getOrderNumber(token, tech_id, s_id, p_id, tvAppointTime.getText().toString().split(" ")[0], coupon_id, price, payment);
                break;
            case R.id.ll_alipay:
                if (!cbAlipay.isChecked()) {
                    payment = "2";
                    cbAlipay.setChecked(true);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_wechat:
                if (!cbWechat.isChecked()) {
                    payment = "1";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(true);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_paypal:
                if (!cbBank.isChecked()) {
                    payment = "3";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(true);
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event) {
        if (event.getFrom() != null)
            switch (event.getFrom()) {
                case "tech":
                    //技师选择
                    tech_id = event.getMessage();
                    tvTechName.setText(event.getTitle());
                    break;
                case "appointment":
                    //预约时间
                    tvAppointTime.setText(event.getMessage());
                    break;
                case "wechat":
                    String message = event.getMessage();
                    if (message.equals("0")) {
                        ToastUtils.showToast("支付成功");
                        startActivity(AppointmentSuccessActivity.createIntent(this,serviceCode));
                    } else if (message.equals("-1")) {
                        ToastUtils.showToast("支付失败");
                    } else if (message.equals("-2")) {
                        ToastUtils.showToast("用户取消");
                    }
                    break;
            }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case REQUEST_COUPON:
                    tvCouponName.setText(data.getStringExtra("couponName"));
                    coupon_id = data.getStringExtra("couponId");
                    txtMoney.setText("金额计算中");
                    mPresenter.caculatePrice(token, p_id, coupon_id);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void setPrice(PriceBean data) {
        price = data.getMoney();
        txtMoney.setText(String.format(ResourcesUtils.getString(R.string.money), price));
    }

    @Override
    public void aliPay(String order_num) {
        new Alipay(this, order_num, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                ToastUtils.showToast("支付成功");
                startActivity(AppointmentSuccessActivity.createIntent(AppointmentActivity.this,order_num));
            }

            @Override
            public void onDealing() {
                ToastUtils.showToast("支付处理中...");
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        ToastUtils.showToast("支付失败:支付结果解析错误");
                        break;

                    case Alipay.ERROR_NETWORK:
                        ToastUtils.showToast("支付失败:网络连接错误");
                        break;

                    case Alipay.ERROR_PAY:
                        ToastUtils.showToast("支付错误:支付码支付失败");
                        break;

                    default:
                        ToastUtils.showToast("支付错误");
                        break;
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showToast("支付取消");
            }
        }).doPay();
    }

    @Override
    public void wxPay(WXPayBean pay_param, String orderNum) {
        serviceCode = orderNum;
        WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
        builder.setAppId(pay_param.getAppid())
                .setPartnerId(pay_param.getPartnerid())
                .setPrepayId(pay_param.getPrepayid())
                .setPackageValue(pay_param.getPackageX())
                .setNonceStr(pay_param.getNoncestr())
                .setTimeStamp(pay_param.getTimestamp())
                .setSign(pay_param.getSign())
                .build().toWXPayNotSign(this, pay_param.getAppid());
    }
}
